package com.xxgc.zde.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.zde.api.WechatLoginApi;
import com.xxgc.zde.api.response.WechatLoginResponse;
import com.xxgc.zde.controller.dto.UserLoginDTO;
import com.xxgc.zde.controller.vo.UserLoginVO;
import com.xxgc.zde.entity.UsersEntity;
import com.xxgc.zde.entity.UsersEntityRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/* ResponseBody + Controller*/
@RestController
@RequestMapping("/login")
@Tag(name = "登录接口")
public class UserLoginController {

    private static final String Appid = "wxea228f049e3a5763";

    private static final String AppSecret = "6111454425d9d5d69a5e7e74423b7c83";

    @Autowired
    private WechatLoginApi wechatLoginApi;
    @Autowired
    private UsersEntityRepository usersEntityRepository;

    @Operation(summary = "测试通讯用")
    @GetMapping("/msg")
    public String msg(){
        return "成功编写了第一个接口";
    }

    @Operation(summary = "用户登录")
    @PostMapping("/userLogin")
    public UserLoginDTO userLogin(@RequestBody UserLoginVO userLoginVO){
        return null;
    }

    @Operation(summary = "微信登陆")
    @PostMapping("/wechatLogin/{code}")
    public String wechatLogin(@PathVariable String code){
        System.out.println("code="+code);
        WechatLoginResponse ac = wechatLoginApi.getUserOpenId(Appid, AppSecret, code, "authorization_code");
        System.out.println("authorization_code="+ac);

         //openid相关操作
        //https://baomidou.com/guides/data-interface/
        QueryWrapper<UsersEntity> qw = new QueryWrapper<>();
        qw.eq("open_id",ac.getOpenid());
        UsersEntity one = usersEntityRepository.getOne(qw);
        if(one == null){//没有这个id，注册
            one = new UsersEntity();
            one.setOpenId(ac.getOpenid());
            usersEntityRepository.save(one);
        }
        return one.getId();
    }
}
